#!/bin/bash

# HLS加密处理流水线脚本
# 完整的MP4到加密HLS流程

set -e  # 遇到错误立即退出

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_debug() {
    if [[ "$ENABLE_DEBUG" == "true" ]]; then
        echo -e "${BLUE}[DEBUG]${NC} $1"
    fi
}

print_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 配置文件路径
CONFIG_FILE="$(dirname "$0")/config.json"

# 加载配置文件
load_config() {
    if [ -f "$CONFIG_FILE" ]; then
        if ! command -v jq &> /dev/null; then
            print_error "请先安装jq: brew install jq"
            exit 1
        fi

        # 从统一配置文件加载配置
        OUTPUT_DIR=$(jq -r '.common.output_dir // empty' "$CONFIG_FILE")
        VIDEO_ID=$(jq -r '.common.video_id // empty' "$CONFIG_FILE")
        SEGMENT_DURATION=$(jq -r '.hls.segment_duration // empty' "$CONFIG_FILE")
        KEY_SERVER_HOST=$(jq -r '.key_server.host // empty' "$CONFIG_FILE")
        KEY_SERVER_PORT=$(jq -r '.key_server.port // empty' "$CONFIG_FILE")
        UPLOAD_TO_COS=$(jq -r '.cos.enable_upload // false' "$CONFIG_FILE")
        AUTO_INCREMENT=$(jq -r '.cos.auto_increment // true' "$CONFIG_FILE")
        START_KEY_SERVER=$(jq -r '.key_server.enable // false' "$CONFIG_FILE")
        ENABLE_DEBUG=$(jq -r '.common.enable_debug // false' "$CONFIG_FILE")

        # 检查必要的配置
        missing_configs=()
        [ -z "$OUTPUT_DIR" ] && missing_configs+=("common.output_dir")
        [ -z "$VIDEO_ID" ] && missing_configs+=("common.video_id")
        [ -z "$SEGMENT_DURATION" ] && missing_configs+=("hls.segment_duration")
        [ -z "$KEY_SERVER_HOST" ] && missing_configs+=("key_server.host")
        [ -z "$KEY_SERVER_PORT" ] && missing_configs+=("key_server.port")

        if [ ${#missing_configs[@]} -gt 0 ]; then
            print_error "配置文件缺少以下必要参数:"
            printf '%s\n' "${missing_configs[@]}"
            exit 1
        fi

        # 如果启用了COS上传，检查相关配置
        if [[ "$UPLOAD_TO_COS" == "true" ]]; then
            COS_SECRET_ID=$(jq -r '.cos.secret_id // empty' "$CONFIG_FILE")
            COS_SECRET_KEY=$(jq -r '.cos.secret_key // empty' "$CONFIG_FILE")
            COS_REGION=$(jq -r '.cos.region // empty' "$CONFIG_FILE")
            COS_BUCKET=$(jq -r '.cos.bucket // empty' "$CONFIG_FILE")

            missing_cos_configs=()
            [ -z "$COS_SECRET_ID" ] && missing_cos_configs+=("cos.secret_id")
            [ -z "$COS_SECRET_KEY" ] && missing_cos_configs+=("cos.secret_key")
            [ -z "$COS_REGION" ] && missing_cos_configs+=("cos.region")
            [ -z "$COS_BUCKET" ] && missing_cos_configs+=("cos.bucket")

            if [ ${#missing_cos_configs[@]} -gt 0 ]; then
                print_error "启用COS上传但缺少以下配置:"
                printf '%s\n' "${missing_cos_configs[@]}"
                exit 1
            fi
        fi

        print_info "已从 $CONFIG_FILE 加载配置"
        if [[ "$ENABLE_DEBUG" == "true" ]]; then
            print_debug "调试模式已启用"
            print_debug "输出目录: $OUTPUT_DIR"
            print_debug "视频ID: $VIDEO_ID"
            print_debug "分片时长: $SEGMENT_DURATION"
            print_debug "密钥服务器: ${KEY_SERVER_HOST}:${KEY_SERVER_PORT}"
            [[ "$UPLOAD_TO_COS" == "true" ]] && print_debug "已启用COS上传"
            [[ "$AUTO_INCREMENT" == "true" ]] && print_debug "已启用自动递增"
        fi
    else
        print_error "配置文件不存在: $CONFIG_FILE"
        exit 1
    fi
}

# 默认配置
INPUT_VIDEO=""
OUTPUT_DIR="./hls_output"
VIDEO_ID="test_video"
SEGMENT_DURATION=10
KEY_SERVER_HOST="0.0.0.0"
KEY_SERVER_PORT=8080
UPLOAD_TO_COS=false
START_KEY_SERVER=false

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -o|--output)
            OUTPUT_DIR="$2"
            shift 2
            ;;
        -i|--video-id)
            VIDEO_ID="$2"
            shift 2
            ;;
        -d|--duration)
            SEGMENT_DURATION="$2"
            shift 2
            ;;
        -s|--key-server)
            START_KEY_SERVER=true
            shift
            ;;
        -u|--upload)
            UPLOAD_TO_COS="true"  # 修改这里，确保是字符串true
            shift
            ;;
        --key-host)
            KEY_SERVER_HOST="$2"
            shift 2
            ;;
        --key-port)
            KEY_SERVER_PORT="$2"
            shift 2
            ;;
        -h|--help)
            show_help
            exit 0
            ;;
        -*)
            print_error "未知选项: $1"
            show_help
            exit 1
            ;;
        *)
            if [[ -z "$INPUT_VIDEO" ]]; then
                INPUT_VIDEO="$1"
            else
                print_error "多余的参数: $1"
                exit 1
            fi
            shift
            ;;
    esac
done

# 检查必要参数
if [[ -z "$INPUT_VIDEO" ]]; then
    print_error "请指定输入视频文件"
    show_help
    exit 1
fi

if [[ ! -f "$INPUT_VIDEO" ]]; then
    print_error "输入文件不存在: $INPUT_VIDEO"
    exit 1
fi

# 检查依赖
check_dependencies() {
    print_info "检查依赖..."
    
    if ! command -v ffmpeg &> /dev/null; then
        print_error "FFmpeg 未安装"
        exit 1
    fi
    
    if ! command -v python3 &> /dev/null; then
        print_error "Python3 未安装"
        exit 1
    fi
    
    print_info "依赖检查通过"
}

# 安装Python依赖
install_python_deps() {
    print_info "安装Python依赖..."
    pip3 install -r "$(dirname "$0")/requirements.txt" || {
        print_error "Python依赖安装失败"
        exit 1
    }
}

# 获取下一个可用的视频ID和输出目录
get_next_video_id() {
    local base_id="$VIDEO_ID"
    local max_number=1
    
    # 检查现有的视频ID编号
    if [[ -d "$OUTPUT_DIR" ]]; then
        for dir in "$OUTPUT_DIR"/*; do
            if [[ -d "$dir" ]]; then
                local dir_name=$(basename "$dir")
                if [[ "$dir_name" =~ ^${base_id}_([0-9]+)$ ]]; then
                    local num=${BASH_REMATCH[1]}
                    if [[ $num -ge $max_number ]]; then
                        max_number=$((num + 1))
                    fi
                elif [[ "$dir_name" == "$base_id" ]]; then
                    max_number=2  # 如果存在基础目录，从2开始
                fi
            fi
        done
    fi
    
    echo "${base_id}_${max_number}"
}

# 生成加密HLS
generate_hls() {
    print_info "开始生成加密HLS..."
    
    # 如果启用了自动递增，获取下一个视频ID
    if [[ "$AUTO_INCREMENT" == "true" ]]; then
        VIDEO_ID=$(get_next_video_id)
        print_info "使用自动递增视频ID: $VIDEO_ID"
    fi
    
    # 获取实际的IP地址用于密钥URI
    local actual_ip=$(ifconfig | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | head -1)
    local key_uri="http://${actual_ip}:${KEY_SERVER_PORT}/key/${VIDEO_ID}"
    local video_output_dir="${OUTPUT_DIR}/${VIDEO_ID}"
    
    python3 "$(dirname "$0")/hls_encrypt.py" \
        "${INPUT_VIDEO}" \
        "${video_output_dir}" \
        --key-uri "${key_uri}" \
        --segment-duration "${SEGMENT_DURATION}" || {
        print_error "HLS生成失败"
        exit 1
    }
    
    print_info "HLS生成完成: $video_output_dir"
}

# 启动密钥服务器
start_key_server() {
    print_info "启动密钥服务器..."
    
    # 检查端口是否被占用
    if lsof -i :$KEY_SERVER_PORT >/dev/null 2>&1; then
        print_warn "端口 $KEY_SERVER_PORT 被占用，尝试终止占用进程..."
        local pid=$(lsof -ti:$KEY_SERVER_PORT)
        if [[ -n "$pid" ]]; then
            kill -9 $pid 2>/dev/null
            sleep 1
            print_info "已终止占用进程: $pid"
        fi
    fi
    
    python3 "$(dirname "$0")/key_server.py" \
        --host "$KEY_SERVER_HOST" \
        --port "$KEY_SERVER_PORT" \
        --keys-dir "$OUTPUT_DIR" &
    
    local server_pid=$!
    echo $server_pid > "${OUTPUT_DIR}/key_server.pid"
    
    # 等待服务器启动
    sleep 2
    
    if kill -0 $server_pid 2>/dev/null; then
        print_info "密钥服务器已启动 (PID: $server_pid)"
        print_info "密钥服务器地址: http://${KEY_SERVER_HOST}:${KEY_SERVER_PORT}"
    else
        print_error "密钥服务器启动失败"
        exit 1
    fi
}

# 上传到COS
upload_to_cos() {
    print_info "上传到COS..."

    local video_output_dir="${OUTPUT_DIR}/${VIDEO_ID}"
    local cos_prefix="hls/${VIDEO_ID}"

    python3 "$(dirname "$0")/cos_upload.py" \
        "$video_output_dir" \
        "$cos_prefix" || {
        print_error "COS上传失败"
        exit 1
    }

    print_info "COS上传完成"
}

# 显示结果
show_results() {
    print_info "=== 处理完成 ==="
    echo
    print_info "输出目录: $OUTPUT_DIR"
    print_info "视频ID: $VIDEO_ID"
    print_info "播放列表: ${OUTPUT_DIR}/${VIDEO_ID}/stream.m3u8"
    
    if [[ "$START_KEY_SERVER" == true ]]; then
        echo
        print_info "密钥服务器: http://${KEY_SERVER_HOST}:${KEY_SERVER_PORT}"
        print_info "密钥URL: http://${KEY_SERVER_HOST}:${KEY_SERVER_PORT}/key/${VIDEO_ID}"
        print_info "停止服务器: kill \$(cat ${OUTPUT_DIR}/key_server.pid)"
    fi
    
    if [[ "$UPLOAD_TO_COS" == true ]] && [[ -f "${OUTPUT_DIR}/${VIDEO_ID}/urls.json" ]]; then
        echo
        print_info "COS URLs:"
        cat "${OUTPUT_DIR}/${VIDEO_ID}/urls.json"
    fi
    
    echo
    print_info "可以使用BetterPlayer测试播放了!"
}

# 清理函数
cleanup() {
    if [[ -f "${OUTPUT_DIR}/key_server.pid" ]]; then
        local pid=$(cat "${OUTPUT_DIR}/key_server.pid")
        if kill -0 $pid 2>/dev/null; then
            print_info "停止密钥服务器..."
            kill $pid
        fi
        rm -f "${OUTPUT_DIR}/key_server.pid"
    fi
}

# 设置清理陷阱
trap cleanup EXIT

# 主流程
main() {
    print_info "开始HLS加密处理流水线..."
    print_info "输入文件: $INPUT_VIDEO"
    print_info "输出目录: $OUTPUT_DIR"
    print_info "视频ID: $VIDEO_ID"
    
    # 如果启用了自动递增，显示提示信息
    if [[ "$AUTO_INCREMENT" == "true" ]]; then
        print_info "自动递增模式已启用"
    fi
    
    check_dependencies
    install_python_deps
    
    # 创建输出目录
    mkdir -p "$OUTPUT_DIR"
    
    # 生成HLS
    generate_hls

    # 生成HLS后再启动密钥服务器
    if [[ "$START_KEY_SERVER" == true ]]; then
        start_key_server
    fi
    
    # 上传到COS
    if [[ "$UPLOAD_TO_COS" == true ]]; then
        upload_to_cos
    fi
    
    show_results
    
    # 如果启动了密钥服务器，保持运行
    if [[ "$START_KEY_SERVER" == true ]]; then
        print_info "密钥服务器正在运行，按 Ctrl+C 停止..."
        wait
    fi
}

load_config
main